package com.hex.campus.backend.hex_campus_backend.controller;

import com.hex.campus.backend.hex_campus_backend.entity.Book;
import com.hex.campus.backend.hex_campus_backend.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/books")
@CrossOrigin(origins = "http://localhost:5173")
public class BookController {

    @Autowired
    private BookService bookService;

    //获取所有教材信息
    @GetMapping
    public ResponseEntity<?> getAllBooks() {
        List<Book> books = bookService.getAllBooks();
        Map<String, Object> response = new HashMap<>();
        response.put("books", books);
        response.put("message", "Books retrieved successfully");
        return ResponseEntity.ok(response);
    }

    //添加一本教材
    @PostMapping
    public ResponseEntity<?> addBook(@RequestBody Book book) {
        try {
            Book savedBook = bookService.addBook(book);
            Map<String, Object> response = new HashMap<>();
            response.put("book", savedBook);
            response.put("message", "Book added successfully");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "Failed to add book: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    //根据关键字搜索教材
    @GetMapping("/search")
    public ResponseEntity<?> searchBooks(@RequestParam String keyword) {
        List<Book> books = bookService.searchBooks(keyword);
        Map<String, Object> response = new HashMap<>();
        response.put("books", books);
        response.put("message", "Search completed successfully");
        return ResponseEntity.ok(response);
    }

    //根据用户ID搜索教材
    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getBooksByUserId(@PathVariable Long userId) {
        List<Book> books = bookService.getBooksByUserId(userId);
        return ResponseEntity.ok(books);
    }

    //删除教材
    @DeleteMapping("/{bookId}")
    public ResponseEntity<?> deleteBook(@PathVariable Long bookId) {
        try {
            bookService.deleteBook(bookId);
            Map<String, String> response = new HashMap<>();
            response.put("message", "Book deleted successfully");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "Failed to delete book: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}